package ru.niir.goodfil.ui.utils;

import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.lang.*;
import java.lang.Process;

/**
 * Класс для создание и восстановления бэкапов mysql при помощи коммандных утилит mysqldump и mysql
 */
public class SimpleMysqlBackuper
{
    private String username;
    private String password;
    private String database;

    public SimpleMysqlBackuper(String username, String password, String database)
    {
        if (StringUtils.isBlank(username))
        {
            throw new IllegalArgumentException("Username cannot be null or empty");
        }

        if (StringUtils.isBlank(password))
        {
            throw new IllegalArgumentException("Password cannot be null or empty");
        }

        if (StringUtils.isBlank(database))
        {
            throw new IllegalArgumentException("Database cannot be null or empty");
        }

        this.username = username;
        this.password = password;
        this.database = database;
    }

    public synchronized void backup(String path) throws IOException
    {
        if (StringUtils.isBlank(database))
        {
            throw new IllegalArgumentException("Path cannot be null or empty");
        }

        String r = path + ".sql";
        String cmd = "mysqldump --opt -u" + username + " -p" + password + " " + database;
        Process p = Runtime.getRuntime().exec(cmd);
        InputStream is = p.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        FileWriter fileW = new FileWriter(r);
        PrintWriter pw = new PrintWriter(fileW);
        String aux = br.readLine();
        while (aux != null)
        {
            pw.println(aux);
            aux = br.readLine();
        }
        pw.close();
        fileW.close();
    }

    public synchronized void restore(String filename) throws IOException
    {
        if (StringUtils.isBlank(database))
        {
            throw new IllegalArgumentException("Filename cannot be null or empty");
        }

        filename = filename + ".sql";
        String[] cmds = {"/bin/sh", "-c", "mysql -u " + username + " -p" + password + " " + database + " < " + filename};
        Process ps = Runtime.getRuntime().exec(cmds);
    }

    private static String loadStream(InputStream in) throws IOException
    {
        int ptr = 0;
        in = new BufferedInputStream(in);
        StringBuffer buffer = new StringBuffer();
        while ((ptr = in.read()) != -1)
        {
            buffer.append((char) ptr);
        }
        return buffer.toString();
    }
}
